//
// Created by hsx on 2025/4/14.
//

#include "connect_manager.h"
#include "daf/daf_event.h"

using namespace Gazella::Daf;

ConnectManager *ConnectManager::getInstance()
{
    static ConnectManager instance;
    return &instance;
}

bool ConnectManager::initUdp()
{
    // init返回非零为连接失败
    while (1)
    {
        if (AutoCmdClient.init(remoteAddr, AutoCmdPort) != 0 || agentServer.init(localAddr, localReportPort) != 0)
        {
            mp_log_error(DEFAULT_LOGGER, "UDP Connect failed");
        }
        else
        {
            mp_log_info(DEFAULT_LOGGER, "UDP Connect Success");
            std::string test = "通信正常";
            AutoCmdClient.send_message(test);
            break;
        }
    }
    agentServer.add_recv_over_callback([&](const std::string &remote_host, int remote_port, std::string &msg)
                                       { parseReport(remote_host, remote_port, msg); });

    return true;
}

void ConnectManager::parseReport(const std::string &remote_host, int remote_port, std::string &msg)
{
    // 目标信息数组（targetinfos）
    DeviceAgentModel::DeviceAgentProperty targetInfosP;
    Gazella::Daf::DafModel::get_instance()->get_property("targetinfos", targetInfosP);
    targetInfosP.mutable_property_array()->Clear(); // 清空旧数组

    std::stringstream ss(msg);
    std::string token;

    while (std::getline(ss, token, ','))
    {
        if (token.empty())
            continue;

        char prefix = token[0];               // 获取前缀（类型）
        std::string id_str = token.substr(1); // 获取目标编号（如 1）
        mp_log_info(DEFAULT_LOGGER, "UDP receive: %s", token.c_str());
        // 获取 target 模板
        DeviceAgentModel::DeviceAgentProperty targetP;
        Gazella::Daf::DafModel::get_instance()->get_property("target", targetP);

        // 设置 target_id
        (*targetP.mutable_property_struct()->mutable_members())["target_id"]
            .mutable_property_string()
            ->set_value(id_str);
        mp_log_info(DEFAULT_LOGGER, "set_target_id: %s", token.c_str());

        // 设置 type
        int type_val = 9; // 默认未知
        if (prefix == 'p')
            type_val = 0; // 人员
        else if (prefix == 'c')
            type_val = 1; // 车辆
        else if (prefix == 'g')
            type_val = 2; // 火炮
        else if (prefix == 'b')
            type_val = 3; // 工事
        else if (prefix == 'o')
            type_val = 4; // 障碍

        (*targetP.mutable_property_struct()->mutable_members())["type"]
            .mutable_property_enum()
            ->set_value(type_val);
        mp_log_info(DEFAULT_LOGGER, "set_target_type: %d", type_val);

        // 你也可以在这里设置 lat/lon/distance 等字段，例：
        // (*targetP.mutable_property_struct()->mutable_members())["lat"]
        //     .mutable_property_float()->set_value(36.123456);

        // 将目标添加进数组
        targetInfosP.mutable_property_array()->add_properties()->CopyFrom(targetP);
    }

    // 最后设置回 targetinfos 属性
    Gazella::Daf::DafModel::get_instance()->set_property("targetinfos", targetInfosP);

    DafEvent::get_instance()->event_once("pubTargetInfos/xyd");
    DafEvent::get_instance()->event_once("pubTargetInfos");
}